package biz.datalk.industrialland.admin.component;

import biz.datalk.industrialland.common.pojo.vo.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.apache.shiro.SecurityUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;

/**
 * Mybatis 拦截器
 * 当以下值没有设置默认值时，自动注入值
 * createBy,createName,createTime,updateBy,updateName,updateTime,sysOrgCode
 *
 * @author tarofang@163.com
 * @date 2019-12-17
 */
@Slf4j
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
@ConditionalOnProperty(name = {"datalk.core.mybatis.interceptor.enable"}, havingValue = "true")
public class DatalkMybatisInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        log.info("sqlCommandType = {}", sqlCommandType);
        Object parameter = invocation.getArgs()[1];
        if (parameter == null) {
            return invocation.proceed();
        }

        if (SqlCommandType.INSERT == sqlCommandType) {
            handleInsert(parameter);
        }

        if (SqlCommandType.UPDATE == sqlCommandType) {
            handleUpdate(parameter);
        }

        return invocation.proceed();
    }

    private void handleInsert(Object parameter) {
        Field[] allFields = getAllFields(parameter);
        if (ArrayUtils.isEmpty(allFields)) {
            return;
        }

        // 获取用户的登录信息
        // 定时任务时，无法获取到用户
        LoginUser sysUser;
        try {
            sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        } catch (Exception ex) {
            log.warn("Not find login user. {}", ex.getMessage());
            sysUser = null;
        }
        Long sysUserId = null;
        String userRealName = "", sysOrgCode = "";
        if (sysUser != null) {
            sysUserId = sysUser.getId();
            userRealName = sysUser.getRealname();
            sysOrgCode = sysUser.getOrgCode();
        }
        Date now = new Date();

        String fieldName;
        for (Field field : allFields) {
            fieldName = field.getName();
            log.debug("------field.name------" + fieldName);
            try {
                setFieldValue(field, "createBy", parameter, sysUserId, Boolean.FALSE);
                setFieldValue(field, "createName", parameter, userRealName, Boolean.FALSE);
                setFieldValue(field, "createTime", parameter, now, Boolean.FALSE);
                //setFieldValue(field, "updateTime", parameter, now, Boolean.FALSE);
                setFieldValue(field, "sysOrgCode", parameter, sysOrgCode, Boolean.FALSE);
            } catch (Exception ex) {
                log.warn(ex.getMessage(), ex);
            }

        }
    }

    private void handleUpdate(Object parameter) {
        Field[] allFields = getAllFields(parameter);
        if (ArrayUtils.isEmpty(allFields)) {
            return;
        }

        // 获取用户的登录信息 定时任务时，无法获取到用户
        LoginUser sysUser;
        try {
            sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        } catch (Exception ex) {
            log.warn("Not find login user. {}", ex.getMessage());
            sysUser = null;
        }
        Long sysUserId = null;
        String userRealName = "";
        if (sysUser != null) {
            sysUserId = sysUser.getId();
            userRealName = sysUser.getRealname();
        }
        Date now = new Date();
        String fieldName;
        for (Field field : allFields) {
            fieldName = field.getName();
            log.debug("------field.name------" + fieldName);
            try {
                setFieldValue(field, "updateBy", parameter, sysUserId, Boolean.TRUE);
                setFieldValue(field, "updateName", parameter, userRealName, Boolean.TRUE);
                setFieldValue(field, "updateTime", parameter, now, Boolean.TRUE);
            } catch (Exception ex) {
                log.warn(ex.getMessage(), ex);
            }

        }

    }

    private void setFieldValue(Field field, String searchFieldName, Object parameter, Object val, boolean isUpdate) throws IllegalAccessException {
        String fieldName = field.getName();
        if (!StringUtils.equals(fieldName, searchFieldName)) {
            return;
        }

        // 取值
        field.setAccessible(true);
        Object originalVal = field.get(parameter);
        field.setAccessible(false);

        // 添加操作
        if (!isUpdate) {
            // 原来值存在 不做任何操作
            if (originalVal != null && !"".equals(originalVal)) {
                return;
            }

            // 设置需要的值
            if (val != null && !"".equals(val)) {
                field.setAccessible(true);
                field.set(parameter, val);
                field.setAccessible(false);
            }
            return;
        }

        // 更新操作
        if (val != null && !"".equals(val)) {
            field.setAccessible(true);
            field.set(parameter, val);
            field.setAccessible(false);
        }


    }

    public static Field[] getAllFields(Object object) {
        Class<?> clazz = object.getClass();
        List<Field> fieldList = new ArrayList<>();
        while (clazz != null) {
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        return fields;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        log.info(properties.toString());
    }
}
